package com.yunbao.hujin.myoss.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 把处理过的文件又重新保存到sd里面 on 2017/11/21.
 */

public class saveBitmapUtil {

//    private static Context context;

    public static String saveBitmapUtil(String number,Bitmap bitmap) {
        long time = System.currentTimeMillis();
        String t = new SimpleDateFormat("yyyy_MM_dd").format(new Date(time));
        String d = new SimpleDateFormat("HH_mm").format(new Date(time));

        // 压缩图片保存的目录路径
        String filePath ="/" + t + "/" + d;


        // 压缩后图片保存的文件名
        String fileName = "photo" + "(" + number + ")" + ".jpg";

        // 压缩图片保存的目录路径
//        File file = new File(Environment.getExternalStorageDirectory().getPath() + "myApp");
        File file = new File(getSDPath() + filePath);
        if (!file.exists()) {
            file.mkdir();
        }
        File dir = new File(file, fileName);//将要保存图片的路径，android推荐这种写法，将目录名和文件名分开，不然容易报错。


        Bitmap bitmap1 = BitmapUtils.compressBySize(dir.getPath(), 1280, 768);
        if (!dir.exists()) {
            try {
                dir.createNewFile();
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dir));

                bitmap1.compress(Bitmap.CompressFormat.JPEG, 30, bos);

                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return dir.getAbsolutePath();
    }

    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取根目录
        } else {
//            context.getCacheDir().getAbsolutePath();// 获取内置内存卡目录
        }
        return sdDir.toString();
    }

}
